"use client";
import { useState, useEffect, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { 
  Card, Table, Button, Input, Space, 
  Tag, Tooltip, Popconfirm, Typography, Image, Select
} from 'antd';
import { useMessage } from '@/hooks/useMessage';
import type { TablePaginationConfig } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined, DownloadOutlined } from '@ant-design/icons';
import { adminAPI, adminUserAPI } from '@/lib/api';
import type { Case, CaseCategory, AdminUser } from '@/lib/api';
import AdminLayout from '@/components/AdminLayout';

const { Text } = Typography;
const { Search } = Input;
const { Option } = Select;

export default function CasesManagement() {
  const message = useMessage();
  const [cases, setCases] = useState<Case[]>([]);
  const [categories, setCategories] = useState<CaseCategory[]>([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
    totalPages: 0,
  });
  const [searchKeyword, setSearchKeyword] = useState('');
  const [selectedCategory, setSelectedCategory] = useState<number | null>(null);
  const [selectedStatus, setSelectedStatus] = useState<boolean | null>(null);
  const [selectedUser, setSelectedUser] = useState<number | null>(null);
  const [users, setUsers] = useState<AdminUser[]>([]);
  const [exportLoading, setExportLoading] = useState(false);
  const router = useRouter();

  // 获取案例列表
  const fetchCases = useCallback(async (page: number, pageSize: number, keyword?: string, categoryId?: number, status?: boolean, userId?: number) => {
    setLoading(true);
    try {
      const params = {
        page,
        limit: pageSize,
        keyword,
        categoryId,
        status,
        userId,
      };

      const response = await adminAPI.getCases(params);
      if (response.success) {
        setCases(response.data.cases);
        setPagination({
          current: response.data.page,
          pageSize: response.data.limit,
          total: response.data.total,
          totalPages: response.data.totalPages,
        });
      }
    } catch (error) {
      console.error('获取案例列表失败:', error);
      message.error('获取案例列表失败');
    } finally {
      setLoading(false);
    }
  }, []);

  // 获取分类列表
  const fetchCategories = useCallback(async () => {
    try {
      const response = await adminAPI.getCaseCategories();
      if (response.success) {
        setCategories(response.data);
      }
    } catch (error) {
      console.error('获取分类列表失败:', error);
    }
  }, []);

  // 获取用户列表
  const fetchUsers = useCallback(async () => {
    try {
      const response = await adminUserAPI.getUsers();
      if (response.success) {
        setUsers(response.data);
      }
    } catch (error) {
      console.error('获取用户列表失败:', error);
    }
  }, []);

  // 删除案例
  const handleDeleteCase = async (id: number) => {
    try {
      const response = await adminAPI.deleteCase(id);
      if (response.success) {
        message.success('删除成功');
        fetchCases(pagination.current, pagination.pageSize, searchKeyword, selectedCategory || undefined, selectedStatus || undefined, selectedUser || undefined);
      }
    } catch (error) {
      console.error('删除案例失败:', error);
      message.error('删除失败');
    }
  };

  // 处理预览 - 直接跳转到前台页面
  const handlePreview = (record: Case) => {
    window.open(`/cases/detail/${record.slug}`, '_blank');
  };

  // 处理搜索
  const handleSearch = (value: string) => {
    setSearchKeyword(value);
    setPagination(prev => ({ ...prev, current: 1 }));
  };

  // 处理分类筛选
  const handleCategoryChange = (value: number | null) => {
    setSelectedCategory(value);
    setPagination(prev => ({ ...prev, current: 1 }));
  };

  // 处理状态筛选
  const handleStatusChange = (value: boolean | null) => {
    setSelectedStatus(value);
    setPagination(prev => ({ ...prev, current: 1 }));
  };

  // 处理用户筛选
  const handleUserChange = (value: number | null) => {
    setSelectedUser(value);
    setPagination(prev => ({ ...prev, current: 1 }));
    // 立即触发数据获取
    fetchCases(
      1,
      pagination.pageSize,
      searchKeyword || undefined,
      selectedCategory || undefined,
      selectedStatus || undefined,
      value || undefined
    );
  };

  // 处理表格变化
  const handleTableChange = (newPagination: TablePaginationConfig) => {
    fetchCases(
      newPagination.current!,
      newPagination.pageSize!,
      searchKeyword || undefined,
      selectedCategory || undefined,
      selectedStatus || undefined,
      selectedUser || undefined
    );
  };

  // 处理新建案例
  const handleAddCase = () => {
    router.push('/admin/cases/edit');
  };

  // 处理编辑案例
  const handleEditCase = (record: Case) => {
    router.push(`/admin/cases/edit?id=${record.id}`);
  };

  // 处理导出
  const handleExport = async () => {
    setExportLoading(true);
    try {
      const blob = await adminAPI.exportCases({
        keyword: searchKeyword || undefined,
        categoryId: selectedCategory || undefined,
        status: selectedStatus || undefined,
        userId: selectedUser || undefined,
      });
      
      // 创建下载链接
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      
      // 生成文件名
      const now = new Date();
      const dateStr = now.toISOString().split('T')[0];
      link.download = `攻略列表_${dateStr}.xlsx`;
      
      // 触发下载
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
    } catch (error) {
      console.error('导出失败:', error);
      message.error('导出失败');
    } finally {
      setExportLoading(false);
    }
  };

  // 初始化数据
  useEffect(() => {
    fetchCategories();
    fetchUsers();
  }, [fetchCategories, fetchUsers]);

  useEffect(() => {
    fetchCases(
      pagination.current,
      pagination.pageSize,
      searchKeyword || undefined,
      selectedCategory || undefined,
      selectedStatus || undefined,
      selectedUser || undefined
    );
  }, [pagination.current, pagination.pageSize, searchKeyword, selectedCategory, selectedStatus, selectedUser, fetchCases]);

  // 表格列定义
  const columns = [
    {
      title: '封面图',
      dataIndex: 'coverImage',
      key: 'coverImage',
      width: 100,
      render: (url: string) => url ? <Image src={url} width={80} height={60} style={{ objectFit: 'cover' }} /> : '无',
    },
    {
      title: '案例标题',
      dataIndex: 'title',
      key: 'title',
      render: (text: string) => <Text strong>{text}</Text>,
      ellipsis: true,
    },
    {
      title: '摘要',
      dataIndex: 'summary',
      key: 'summary',
      width: 200,
      render: (summary: string) => (
        <Text ellipsis={{ tooltip: summary }}>
          {summary || '-'}
        </Text>
      ),
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
      width: 120,
      render: (category: { name: string } | undefined) => (
        <Tag color="blue">{category?.name || '-'}</Tag>
      ),
    },
    {
      title: '作者',
      dataIndex: 'author',
      key: 'author',
      width: 120,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      render: (status: boolean) => (
        <Tag color={status ? "green" : "red"}>
          {status ? "已发布" : "草稿"}
        </Tag>
      ),
    },
    {
      title: '置顶',
      dataIndex: 'isTop',
      key: 'isTop',
      width: 60,
      render: (isTop: boolean) => (
        <Tag color={isTop ? "orange" : "default"}>
          {isTop ? "置顶" : "-"}
        </Tag>
      ),
    },
    {
      title: '推荐',
      dataIndex: 'isRecommend',
      key: 'isRecommend',
      width: 60,
      render: (isRecommend: boolean) => (
        <Tag color={isRecommend ? "purple" : "default"}>
          {isRecommend ? "推荐" : "-"}
        </Tag>
      ),
    },
    {
      title: '浏览量',
      dataIndex: 'views',
      key: 'views',
      width: 80,
      render: (views: number) => (
        <span>
          <EyeOutlined style={{ marginRight: 4 }} />
          {views.toLocaleString()}
        </span>
      ),
    },
    // {
    //   title: '点赞',
    //   dataIndex: 'likes',
    //   key: 'likes',
    //   width: 60,
    // },
    // {
    //   title: '评论',
    //   dataIndex: 'comments',
    //   key: 'comments',
    //   width: 60,
    // },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 150,
      render: (date: string) => new Date(date).toLocaleDateString(),
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right' as const,
      width: 150,
      render: (_: unknown, record: Case) => (
        <Space size="small">
          <Tooltip title="预览">
            <Button 
              type="text" 
              icon={<EyeOutlined />} 
              onClick={() => handlePreview(record)}
            />
          </Tooltip>
          <Tooltip title="编辑">
            <Button 
              type="text" 
              icon={<EditOutlined />} 
              onClick={() => handleEditCase(record)}
            />
          </Tooltip>
          <Popconfirm
            title="确定要删除这个案例吗？"
            onConfirm={() => handleDeleteCase(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Tooltip title="删除">
              <Button type="text" danger icon={<DeleteOutlined />} />
            </Tooltip>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <AdminLayout>
      <Card
        title="案例管理"
        extra={
          <Space>
            <Button
              icon={<DownloadOutlined />}
              onClick={handleExport}
              loading={exportLoading}
            >
              导出Excel
            </Button>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={handleAddCase}
            >
              新建案例
            </Button>
          </Space>
        }
      >
        <div style={{ marginBottom: 16 }}>
          <Space>
            <Search
              placeholder="输入关键词搜索"
              onSearch={handleSearch}
              enterButton
              style={{ width: 300 }}
            />
            <Select
              placeholder="选择分类"
              allowClear
              style={{ width: 150 }}
              onChange={handleCategoryChange}
              value={selectedCategory}
            >
              {categories.map(category => (
                <Option key={category.id} value={category.id}>
                  {category.name}
                </Option>
              ))}
            </Select>
            <Select
              placeholder="选择状态"
              allowClear
              style={{ width: 120 }}
              onChange={handleStatusChange}
              value={selectedStatus}
            >
              <Option value={true}>已发布</Option>
              <Option value={false}>草稿</Option>
            </Select>
            <Select
              placeholder="选择创作者"
              allowClear
              showSearch
              filterOption={(input, option) =>
                String(option?.children || '').toLowerCase().includes(input.toLowerCase())
              }
              style={{ width: 150 }}
              onChange={handleUserChange}
              value={selectedUser}
            >
              {users.map(user => (
                <Option key={user.id} value={user.id}>
                  {user.username}
                </Option>
              ))}
            </Select>
          </Space>
        </div>
        <Table
          columns={columns}
          dataSource={cases}
          rowKey="id"
          loading={loading}
          pagination={{ 
            ...pagination, 
            total: pagination.total,
            showTotal: (total, range) => `共 ${total} 条记录，第 ${range[0]}-${range[1]} 条`,
            showSizeChanger: true,
            showQuickJumper: true,
            pageSizeOptions: ['10', '20', '50', '100'],
            showLessItems: true,
          }}
          onChange={handleTableChange}
          scroll={{ x: 1500 }}
        />
      </Card>
    </AdminLayout>
  );
}